const multer = require('multer');
const fs = require('fs')
const path = require('path')
const {
    mysql,
    pool,
    router,
    Result,
    Myquery
} = require('../../connect');

let upload = multer({
    dest: './uploads/'
})
router.post('/img', upload.single('file'), function (req, res, next) {
    //读取文件路径(uploads/文件夹下面的新建的图片地址)       
    console.log(req.file, 'file');
    fs.readFile(req.file.path, (err, data) => {
        //如果读取失败           
        if (err) {
            return res.send('上传失败')
        }
        //如果读取成功          
        //声明图片名字为时间戳和随机数拼接成的，尽量确保唯一性         
        let time = Date.now() + parseInt(Math.random() * 999) + parseInt(Math.random() * 2222);
        //拓展名           
        let extname = req.file.mimetype.split('/')[1]
        //拼接成图片名      
        let keepname = time + '.' + extname
        let __basename = './uploads'
        //三个参数           
        //1.图片的绝对路径      
        //2.写入的内容           
        //3.回调函数         
        fs.writeFile(path.join(__basename, '/public/img/' + keepname), data, (err) => {
            if (err) {
                console.log(err, 'err')
                return res.send('写入失败', err)
            }
            res.send({
                err: 0,
                msg: '上传ok',
                // data: data
                data: '/public/img/' + keepname
            })
        });
    });
});

module.exports = router